package com.watson.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author watson
 * @date 2021/8/2 14:53
 * @Description: 自旋锁
 **/
public class LocksDemo3 {
    //  int 0 默认值
    // Thread null
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public static void main(String[] args) throws InterruptedException {
        LocksDemo3 locksDemo3 = new LocksDemo3();
        new Thread(() -> {
            locksDemo3.mylock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            locksDemo3.myUnLock();
        }, "T1").start();
        //保证前面的线程先拿到锁
        TimeUnit.SECONDS.sleep(3);
        new Thread(() -> {
            locksDemo3.mylock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            locksDemo3.myUnLock();
        }, "T2").start();
    }

    //加锁
    public void mylock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "===>mylock");
        // 自旋锁
        while (!atomicReference.compareAndSet(null, thread)) {
        }
    }

    // 解锁
    public void myUnLock() {
        Thread r = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "===>myunlock");
        atomicReference.compareAndSet(r, null);
    }


}



